// pages/patient/patient_info/patient_info.js
var api = require('../../../config/api.js');
const util = require('../../../utils/util.js');

const app = getApp();
var submitting = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    disabled: false,
    id: 0,
    userId: '',
    sex: 0,
    date: '2016-09-01',
    name: '',
    height: '',
    weight: '',
    phone: '',
    nation: '',
    job: '',
    marry: '未婚',
    education: '',
    paytype: '自费',
    income: '',
    addr: '城市',
    jobNum: '',
    arm:'',
    place:'',
    vein: '',
    orien: '',
    phase: '',
    terminal: '',
    array: ['汉族','阿昌族','白族','保安族','布朗族','布依族','朝鲜族','达斡尔族','傣族','德昂族','侗族','东乡族','独龙族','鄂伦春族','俄罗斯族','鄂温克族','高山族','仡佬族','哈尼族','哈萨克族','赫哲族','回族','基诺族','京族','景颇族','柯尔克孜族','拉祜族','黎族','傈僳族','珞巴族','满族','毛南族','门巴族','蒙古族','苗族','仫佬族','纳西族','怒族','普米族','羌族','撒拉族','畲族','水族','塔吉克族','塔塔尔族','土族','土家族','佤族','维吾尔族','乌兹别克族','锡伯族','瑶族','彝族','裕固族','藏族','壮族'],
    index: 0,
    carrerarray: ['教师','工人','记者','演员','厨师','医生','护士','司机','军人','律师','商人','会计','店员','出纳','作家','导游','模特','警察','歌手','画家','裁缝','翻译','法官','保安','花匠','服务员','清洁工','建筑师','理发师','采购员','设计师','消防员','机修工','推销员','魔术师','模特儿','邮递员','售货员','救生员','运动员','工程师','飞行员','管理员','机械师','经纪人','审计员','漫画家','园艺师','科学家','主持人'],
    careerindex:0,
    eduarray: ['小学','初中','高中','大学','硕士','博士','博士后'],
    eduindex:0,
    incomearray: ['1000 ~ 2000','2001 ~ 3000','3000 以上'],
    encomeindex:0,
    items: [
      {value: 'Marry', name: '已婚', checked: true},
      {value: 'Single', name: '未婚', checked: false},
    ],
    sexItem: [
      {value: 0, name: '男', checked: true},
      {value: 1, name: '女', checked: false},
    ],
    payitems: [
      {value: 'medicalInsurance', name: '医保', checked: true},
      {value: 'ownExpense', name: '自费',checked: false},
    ],
    homeArray: ['城市','农村'],
    homeIndex:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

      this.getPatientInfofromServer();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)

    const items = this.data.items
    for (let i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].value == e.detail.value
    }

    this.setData({
      items
    })

    for (let i = 0, len = items.length; i < len; ++i) {
      if(items[i].checked) {
          this.setData({
            marry: items[i].name
          })
      }
    }
  },
  sexRadioChange(e) {
    console.log('sexRadioChange发生change事件，携带value值为：', e.detail.value)

    const sexItem = this.data.sexItem
    for (let i = 0, len = sexItem.length; i < len; ++i) {
      console.log('sexRadioChange发生change事件，sexItem[i].value ', sexItem[i].value)
      sexItem[i].checked = sexItem[i].value == e.detail.value
      console.log('sexRadioChange发生change事件，sexItem[i].checked值为：', sexItem[i].checked)
    }

    this.setData({
      sexItem
    })

    for (let i = 0, len = sexItem.length; i < len; ++i) {
      console.log('sexRadioChange发生change事件，sexItem[i].checked值为：', sexItem[i].checked)
      if(sexItem[i].checked) {
          this.setData({
            sex: sexItem[i].value
          })
      }
    }
  },
  payitemRadioChange(e) {
    console.log('payitemRadioChange发生change事件，携带value值为：', e.detail.value)

    const payitems = this.data.payitems
    for (let i = 0, len = payitems.length; i < len; ++i) {
      payitems[i].checked = payitems[i].value == e.detail.value
    }

    this.setData({
      payitems
    })

    for (let i = 0, len = payitems.length; i < len; ++i) {
      if(payitems[i].checked) {
        this.setData({
          paytype: payitems[i].name
        })
      }
    }
  },

  sendPatientinfotoServer: function(wxCode) {
    let that = this;
    var birthday = util.getTimeStamp(that.data.date);
    console.log('sendPatientinfotoServer：userId:' + app.globalData.userId
        + 'sex = ' + that.data.sex
        + 'name = ' + that.data.name
        + 'height = ' + that.data.height
        + 'weight = ' + that.data.weight
        + 'phone = ' + that.data.phone
        + 'nation = ' + that.data.array[that.data.index]
        + 'job = ' + that.data.carrerarray[that.data.careerindex]
        + 'marry = ' + that.data.marry
        + 'education = ' + that.data.eduarray[that.data.eduindex]
        + 'paytype = ' + that.data.paytype
        + 'income = ' + that.data.incomearray[that.data.encomeindex]
        + 'addrType = ' + that.data.homeArray[that.data.homeIndex]
        + 'jobNum = ' + that.data.jobNum
        + 'birthday = ' + birthday);
            
        console.log("sendPatientinfotoServer date = " + util.timestampFormatDate(birthday, 'yyyy-MM-dd'));
        if(submitting){
          console.log("on submitting ...");
          return;
        }
        submitting = true;
        wx.request({
          url: api.PatientInfoSubmit,
          data: {
                id: that.data.id,
                userId: app.globalData.userId,
                sex: that.data.sex,
                name: that.data.name,
                birthday: birthday,
                height: that.data.height,
                weight: that.data.weight,
                phone: that.data.phone,
                nation: that.data.array[that.data.index],
                job: that.data.carrerarray[that.data.careerindex],
                marry: that.data.marry,
                education: that.data.eduarray[that.data.eduindex],
                paytype: that.data.paytype,
                income: that.data.incomearray[that.data.encomeindex],
                addrType: that.data.homeArray[that.data.homeIndex],
                jobnum: that.data.jobNum,
                arm: that.data.arm,
                place: that.data.place,
                vein: that.data.vein,
                orien: that.data.orien,
                phase: that.data.phase,
                terminal: that.data.terminal
          },
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          success: function(res) {
            submitting = false;
            if (res.data.errno == 0) {
              wx.showModal({
                title: '资料已提交，请等待审核',
                content: res.data.errmsg,
                showCancel: false,
                success (res) {
                  wx.switchTab({
                    url: '/pages/patient/home/home',
                  });
                }
              });
              console.log("sendPatientinfotoServer response: " + JSON.stringify(res));
              console.log("res.data.data.id: " + res.data.data.id);
              console.log("res.data.data.nurseId: " + res.data.data.nurseId);

              let userInfo = wx.getStorageSync('userInfo');
              app.globalData.metaId = res.data.data.id;
              userInfo.metaId = res.data.data.id;
              app.globalData.myNurseId = res.data.data.nurseId;
              userInfo.role = 'patient';
              wx.setStorageSync('userInfo', userInfo);

              console.log("app.globalData.metaId: " + app.globalData.metaId + " app.globalData.myNurseId = " + app.globalData.myNurseId);
            } else {
              console.log('sendPatientinfotoServer res = ' + JSON.stringify(res));
              wx.showModal({
                title: '错误信息',
                content: res.data.errmsg,
                showCancel: false
              });
            }
          },
          fail: function (err) {
            console.log("submit fail ...");
            submitting = false;
          }
        });
  },
  submitPatientInfo() {
    var that = this;
    that.setData({
      disabled: true
    });
    that.sendPatientinfotoServer();
  },
  bindPatientNameInput: function(event) {
    console.log(event.detail);
    this.setData({
      name: event.detail
    });
  },
  bindPatientHeightInput: function(event) {
    console.log(event.detail);
    this.setData({
      height: event.detail
    });
  },
  bindPatientWeightInput: function(event) {
    console.log(event.detail);
    this.setData({
      weight: event.detail
    });
  },
  bindMobileNumberInput: function(event) {
    console.log(event.detail);
    this.setData({
      phone: event.detail
    });
  },
  bindNurseNumberInput: function(event) {
    console.log(event.detail);
    this.setData({
      jobNum: event.detail
    });
  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
        index: e.detail.value,
        nation: this.data.array[this.data.index]
    })
  },
  bindCareerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      careerindex: e.detail.value,
      job: this.data.carrerarray[this.data.careerindex]
    })
  },
  bindEducationChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      eduindex: e.detail.value,
      education: this.data.eduarray[this.data.eduindex]
    })
  },
  bindIncomeChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      encomeindex: e.detail.value,
      income: this.data.incomearray[this.data.encomeindex]
    })
  },
  bindHomeChange: function(e) {
    console.log('bindHomeChange picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      homeIndex: e.detail.value,
      addr: this.data.homeArray[this.data.homeIndex]
    })
  },
  bindDateChange: function (e) {
    console.log('bindDateChange picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  getPatientInfofromServer: function(){
    let that = this;
    console.log("getPatientInfofromServer with url: " + api.PatientInfoList + ' app.globalData.id ' + app.globalData.id);
    util.request(api.PatientInfoList,{
      id: app.globalData.metaId
    }).then(function(res){
      console.log("getPatientInfofromServer" + JSON.stringify(res));
      var info_temp = res['data'];
      if(info_temp!=null && info_temp!=""){
        console.log("getNurseInfofromServer info_temp " + info_temp['name']);
        var date = util.timestampFormatDate(info_temp['birthday'], 'yyyy-MM-dd');
        console.log("getNurseInfofromServer date = " + date);
        that.setData({
            id: info_temp['id'],
            userId: info_temp['userId'],
            sex: info_temp['sex'],
            name: info_temp['name'],
            date: date,
            height: info_temp['height'],
            weight: info_temp['weight'],
            phone: info_temp['phone'],
            nation: info_temp['nation'],
            job: info_temp['job'],
            marry: info_temp['marry'],
            education: info_temp['education'],
            paytype: info_temp['paytype'],
            income: info_temp['income'],
            addr: info_temp['addrType'],
            jobNum: info_temp['jobnum'],
            arm: info_temp['arm'],
            place: info_temp['place'],
            vein: info_temp['vein'],
            orien: info_temp['orien'],
            phase: info_temp['phase'],
            terminal: info_temp['terminal'],
          });


          let sexItem = that.data.sexItem;
          for (let i = 0, len = sexItem.length; i < len; ++i) {
            console.log('query sex：' + sexItem[i].name + " that.data.sex " + that.data.sex)
            if(sexItem[i].value == that.data.sex) {
              sexItem[i].checked = true;
              sexItem[1-i].checked = false;
              that.setData({
                sexItem: sexItem
              });
              console.log('query sex set ：', sexItem[i].name + ' sexItem[i].checked = ' + sexItem[i].checked);
            }
          }
      
          let array = that.data.array;
          let index = that.data.index;
          for (let i = 0, len = array.length; i < len; ++i) {
            console.log('query nation', array[i])
            if(array[i] == that.data.nation) {
              that.setData({
                index: i
              })
              console.log('query nation set index：' + index);
            }
          }
      
          
          let carrerarray = that.data.carrerarray;
          let careerindex = that.data.careerindex;
          for (let i = 0, len = carrerarray.length; i < len; ++i) {
            console.log('query job' + carrerarray[i] + ' that.data.job = ' + that.data.job);
            if(carrerarray[i] == that.data.job) {
              that.setData({
                careerindex: i
              })
              console.log('query job set careerindex：' + careerindex);
            }
          }
      
          let items = that.data.items;
          for (let i = 0, len = items.length; i < len; ++i) {
            console.log('query marry：', items[i].name)
            if(items[i].name == that.data.marry) {
              items[i].checked = true;
              items[1-i].checked = false;
              that.setData({
                items: items
              });
              console.log('query marry set ：', items[i].name + ' sexItem[i].checked = ' + items[i].checked);
            }
          }
      
          let eduarray = that.data.eduarray;
          let eduindex = that.data.eduindex;
          for (let i = 0, len = eduarray.length; i < len; ++i) {
            console.log('query edu', eduarray[i])
            if(eduarray[i] == that.data.education) {
              that.setData({
                eduindex: i
              })
              console.log('query edu set eduindex：' + eduindex);
            }
          }
      
      
          let payitems = that.data.payitems;
          for (let i = 0, len = payitems.length; i < len; ++i) {
            console.log('query paytype: ', payitems[i].name)
            if(payitems[i].name == that.data.paytype) {
              payitems[i].checked = true;
              payitems[1-i].checked = false;
              that.setData({
                payitems: payitems
              });
              console.log('query paytype set ：', payitems[i].name + ' payitems[i].checked = ' + payitems[i].checked);
            }
          }
      
          let incomearray = that.data.incomearray;
          let encomeindex = that.data.encomeindex;
          for (let i = 0, len = incomearray.length; i < len; ++i) {
            console.log('query income', incomearray[i])
            if(incomearray[i] == that.data.income) {
              that.setData({
                encomeindex: i
              })
              console.log('query income set eduindex：' + encomeindex);
            }
          }
      
          let homeArray = that.data.homeArray;
          let homeIndex = that.data.homeIndex;
          for (let i = 0, len = homeArray.length; i < len; ++i) {
            console.log('query home', homeArray[i])
            if(homeArray[i] == that.data.addr) {
              that.setData({
                homeIndex: i
              })
              console.log('query home set eduindex：' + homeIndex);
            }
          }

        }
    });

  }
})